import { stringify } from "query-string";
import router from "umi/router"; // eslint-disable-line
import Axios from "axios";
import { notification } from "antd";
import config from "config";
import { request as fetch, uploadFile } from "@cbd/fetch";
import "antd/lib/notification/style/index.css";

// 业务成功检查
const checkCode = (response, more) => {
  const { errRedirectCode, errCode,  checkCode: checkCodeFunc } =
    config || {};

  // const redirectURL = response.data[redirectCode];
  const { code } = response || {}; // 未登录返回{ code： 501 }, 正常情况返回 { errCode: 0 }
  if (code === errRedirectCode) {
    // const redirectURL = response.data[redirectCode];
    // window.location.href = redirectURL + encodeURIComponent(window.location.href);
    setTimeout(() => {
      window.location.href = `${response.data.loginPageUrl}${encodeURIComponent(
        `${location.origin}/flowplatform-web`,
      )}`;
    }, 500);
  }


  const { isCheck = true } = more;
  // isCheck > checkCodeFunc
  if (
    !isCheck ||
    (typeof checkCodeFunc === "function" && checkCodeFunc(response, more))
  ) {
    return response;
  } else if (`${response.errCode}` === `${errCode}`) {
    return response;
  }

  // 暂时屏蔽此功能，考虑到后端鉴权失败不会返回errCode的情况
  // if (isCheck && `${response.errCode}` === `${errRedirectCode}`) {
  //   // 权限无效处理
  //   // 强迫刷新页面到login
  //   if (errRedirectURL && !/\/login/.test(window.location.href)) {
  //     window.location.href = errRedirectURL;
  //   }
  // }

  const errortext = response.errMsg || "后端接口返回异常";
  const error = new Error(response.errCode);
  error.errCode = response.errCode;
  error.errortext = errortext;
  error.datas = response.datas || {};
  throw error;
};

export default function request(url, options, more = {}) {
  return fetch(url, options)
    .then(resData => checkCode(resData, more))
    .catch(err => {
      const { messageType = "error" } = more;
      const { errCode, errortext } = err;
      notification[messageType]({
        message: `请求错误 ${errCode}: ${url}`,
        description: errortext,
      });
      if (errCode <= 504 && errCode >= 500) {
        router.push("/exception/500");
      }
      if (errCode >= 404 && errCode < 422) {
        router.push("/exception/404");
      }
      if (errCode === "-1") {
        router.push(`/exception/500?msg=${errortext}`);
      }
      return { ...err, message: JSON.stringify({ url, options }) };
    });
}

const get = (url, data, more = {}) =>
  request(
    `${url}?${stringify(data)}`,
    {
      method: "GET",
    },
    more
  );

const post = (url, data, more = {}) =>
  request(
    url,
    {
      method: "POST",
      body: JSON.stringify(data),
    },
    more
  );

const post2 = (url, params) => {
    return Axios({
      url,
      method: "post",
      data: params,
      processData: false, // 不处理数据
      contentType: false, // 不设置内容类型
    }).then(res => {
      return res;
    });
  };
const put = (url, data, more = {}) =>
  request(
    url,
    {
      method: "PUT",
      body: JSON.stringify(data),
    },
    more
  );
const del = (url, data, more = {}) =>
  request(
    url,
    {
      method: "DELETE",
      body: JSON.stringify(data),
    },
    more
  );

export { request, get, post,post2, put, del, uploadFile };
